package org.groupg.project;


import com.beust.jcommander.JCommander;
import org.groupg.project.config.ConfigLoader;
import org.groupg.project.config.ProxyConfig;
import org.groupg.project.config.RuleConfig;
import org.groupg.project.server.HttpProxyServer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        ProxyServerArgs params = new ProxyServerArgs();
        JCommander jCommander = JCommander.newBuilder()
                .addObject(params)
                .build();

        try {
            jCommander.parse(args);

            if (params.isHelp()) {
                jCommander.usage();
                return;
            }

            // 处理示例配置文件生成
            if (params.getExamplesOutputDir() != null) {
                ExampleConfigGenerator.generateExampleConfigs(params.getExamplesOutputDir());
                return;
            }

            // 检查是否有配置文件
            if (!params.hasConfigs()) {
                System.err.println("并非合理的配置文件，请重新指定或检查");
                jCommander.usage();
                return;
            }

            // 合并所有配置文件的规则
            ProxyConfig mergedConfig = new ProxyConfig();
            Map<Integer, List<RuleConfig>> portRules = new HashMap<>();

            for (String configPath : params.getConfigPaths()) {
                ProxyConfig config = ConfigLoader.loadConfig(configPath);
                config.getPortRules().forEach((port, rules) -> portRules.merge(port, rules, (existingRules, newRules) -> {
                    List<RuleConfig> merged = new ArrayList<>(existingRules);
                    merged.addAll(newRules);
                    return merged;
                }));
            }

            mergedConfig.setPortRules(portRules);

            if (mergedConfig.getPortRules().isEmpty()) {
                System.err.println("配置文件参数为空！");
                return;
            }

            // 打印加载的端口信息
            System.out.println("加载代理到端口: " +
                String.join(", ", mergedConfig.getPortRules().keySet()
                    .stream().map(Object::toString).toArray(String[]::new)));

            // 启动服务器
            HttpProxyServer server = new HttpProxyServer(mergedConfig);
            server.start();

        } catch (Exception e) {
            System.err.println("出现异常: " + e.getMessage());
            jCommander.usage();
        }
    }
}